package com.example.bysj.util;
//201902104061徐中堂
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class FileUtil {
    public static String uploadFile(MultipartFile file, String filePath) throws Exception {
        File targetFile = new File(filePath);
        String fileName = file.getOriginalFilename();
        String newFileName = renameToUUID(fileName);
        //如果路径不存在，创建文件夹
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }//创建并写文件
        FileOutputStream out = new FileOutputStream(filePath + newFileName);
        out.write(file.getBytes());
        out.flush(); //清空缓冲区
        out.close();
        return fileName;
    }
    /**
     * 重命名
     * @param fileName
     * @return
     */
    private static String renameToUUID (String fileName){
        return UUID.randomUUID()+"."+fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 获得所有文件文件名
     * @param path 路径
     * @return 文件集合
     */
    public static List<String> getFileNamesFromDir(String path){
        List<String> fns = new ArrayList<String>();
        String[] list = new File(path).list();
        for (int i = 0;i<list.length;i++){
            fns.add(list[i]);
        }
        return fns;
    }

    /**
     * 下载文件
     * @param filepath 文件路径
     * @param filename 文件名
     * @param response 响应
     * @throws IOException
     */
    public static void downloadFile(String filepath, String filename, HttpServletResponse response) throws IOException{
        File file = new File(filepath + "/" + filename);
        if (file.exists()){//判断文件是否存在
            // 创建输入对象
            FileInputStream fis = new FileInputStream(file);
            //设置response对象的相关格式
            response.setContentType("application/force-download;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition","attachment;fileName=" + filename);
            // 创建输出对象
            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while (len!=-1){
                len = fis.read(buf);
                os.write(buf,0,len);
            }
            System.out.println("----------file download---" + filename);
            fis.close();
        }
    }
}
